package com.hhit.zhgd.utils

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit

@Component
class RedisUtil {
    private val logger: Logger = LoggerFactory.getLogger(RedisUtil::class.java)
    @Autowired
    private var redisTemplate: RedisTemplate<String, Any>? = null

    fun RedisUtil(redisTemplate: RedisTemplate<String, Any>?) {
        this.redisTemplate = redisTemplate
    }


    // ===================================common===================================


    // ===================================common===================================
    /**
     * 指定缓存失效时间
     * @param key
     * @param time
     * @return
     */
    fun expire(key: String, time: Long): Boolean {
        return try {
            if (time > 0) {
                redisTemplate!!.expire(key, time, TimeUnit.SECONDS)
            }
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 根据key获取过期时间
     * @param key 键不能为null
     * @return
     */
    fun getExpire(key: String): Long {
        return redisTemplate!!.getExpire(key, TimeUnit.SECONDS)
    }

    /**
     * 判断key是否存在
     * @param key
     * @return
     */
    fun hasKey(key: String): Boolean {
        return try {
            redisTemplate!!.hasKey(key)
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值或多个
     */
    /*@SuppressWarnings("unchecked")
    public void del(String... key)
    {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }*/


    // ===================================String===================================


    /**
     * 删除缓存
     * @param key 可以传一个值或多个
     */
    /*@SuppressWarnings("unchecked")
    public void del(String... key)
    {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }*/
    // ===================================String===================================
    /**
     * 普通缓存获取
     * @param key
     * @return
     */
    operator fun get(key: String?): Any? {
        return if (key == null) null else redisTemplate!!.opsForValue()[key]
    }

    /**
     * 普通缓存放入
     * @param key
     * @param value
     * @return
     */
    operator fun set(key: String, value: Any): Boolean {
        return try {
            redisTemplate!!.opsForValue()[key] = value
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 普通缓存放入并设置时间
     * @param key
     * @param value
     * @param time 时间(秒) time要大于0，如果time小于等于0，将设置无限期
     * @return
     */
    operator fun set(key: String, value: Any, time: Long): Boolean {
        return try {
            if (time > 0) {
                redisTemplate!!.opsForValue()[key, value, time] = TimeUnit.SECONDS
            } else {
                set(key, value)
            }
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 递增
     * @param key
     * @param delta
     * @return
     */
    fun incr(key: String, delta: Long): Long {
        if (delta < 0) {
            throw RuntimeException("递增因子必须大于0")
        }
        return redisTemplate!!.opsForValue().increment(key, delta)!!
    }

    /**
     * 递减
     * @param key
     * @param delta
     * @return
     */
    fun decr(key: String, delta: Long): Long {
        if (delta < 0) {
            throw RuntimeException("递减因子必须大于0")
        }
        return redisTemplate!!.opsForValue().increment(key, -delta)!!
    }


    // ===================================Map===================================


    // ===================================Map===================================
    /**
     * HashGet
     * @param key 不能为null
     * @param item 不能为null
     * @return
     */
    fun hget(key: String, item: String?): Any? {
        return redisTemplate!!.opsForHash<Any, Any>()[key, item!!]
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key
     * @return
     */
    fun hmget(key: String): Map<Any, Any>? {
        return redisTemplate!!.opsForHash<Any, Any>().entries(key)
    }

    /**
     * HashSet
     * @param key
     * @param map
     * @return
     */
    fun hmset(key: String, map: Map<String, Any>?): Boolean {
        return try {
            redisTemplate!!.opsForHash<Any, Any>().putAll(key, map!!)
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * HashSet 并设置时间
     * @param key
     * @param map
     * @param time
     * @return
     */
    fun hmset(key: String, map: Map<String, Any>?, time: Long): Boolean {
        return try {
            redisTemplate!!.opsForHash<Any, Any>().putAll(key, map!!)
            if (time > 0) {
                expire(key, time)
            }
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key
     * @param item
     * @param value
     * @return
     */
    fun hset(key: String, item: String, value: Any): Boolean {
        return try {
            redisTemplate!!.opsForHash<Any, Any>().put(key, item, value)
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key
     * @param item
     * @param value
     * @param time  如果已存在的hash表有时间,这里将会替换原有的时间
     * @return
     */
    fun hset(key: String, item: String, value: Any, time: Long): Boolean {
        return try {
            redisTemplate!!.opsForHash<Any, Any>().put(key, item, value)
            if (time > 0) {
                expire(key, time)
            }
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 删除hash表中的值
     * @param key
     * @param item
     */
    fun hdel(key: String, vararg item: Any?) {
        redisTemplate!!.opsForHash<Any, Any>().delete(key, *item)
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key
     * @param item
     * @return
     */
    fun hHasKey(key: String, item: String?): Boolean {
        return redisTemplate!!.opsForHash<Any, Any>().hasKey(key, item!!)
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     * @param key
     * @param item
     * @param by
     * @return
     */
    fun hincr(key: String, item: String, by: Double): Double {
        return redisTemplate!!.opsForHash<Any, Any>().increment(key, item, by)
    }

    /**
     * hash递减
     * @param key
     * @param item
     * @param by
     * @return
     */
    fun hdecr(key: String, item: String, by: Double): Double {
        return redisTemplate!!.opsForHash<Any, Any>().increment(key, item, -by)
    }


    // ===================================set===================================


    // ===================================set===================================
    /**
     * 根据key获取Set中的所有值
     * @param key
     * @return
     */
    fun sGet(key: String): Set<Any>? {
        return try {
            redisTemplate!!.opsForSet().members(key)
        } catch (e: Exception) {
            logger.error(key, e)
            null
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key
     * @param value
     * @return
     */
    fun sHasKey(key: String, value: Any?): Boolean {
        return try {
            val result = redisTemplate?.opsForSet()?.isMember(key, value)
            return result?.get(key)?:false
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 将数据放入set缓存
     * @param key
     * @param values
     * @return
     */
    fun sSet(key: String, vararg values: Any?): Long {
        return try {
            redisTemplate!!.opsForSet().add(key, *values)!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }

    /**
     * 将set数据放入缓存
     * @param key
     * @param time
     * @param values
     * @return
     */
    fun sSetAndTime(key: String, time: Long, vararg values: Any?): Long {
        return try {
            val count = redisTemplate!!.opsForSet().add(key, *values)
            if (time > 0) expire(key, time)
            count!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }

    /**
     * 获取set缓存的长度
     * @param key
     * @return
     */
    fun sGetSetSize(key: String): Long {
        return try {
            redisTemplate!!.opsForSet().size(key)!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }

    /**
     * 移除值为value的
     * @param key
     * @param values
     * @return
     */
    fun setRemove(key: String, vararg values: Any?): Long {
        return try {
            val count = redisTemplate!!.opsForSet().remove(key, *values)
            count!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }


    // ===================================zset===================================


    // ===================================zset===================================
    /**
     * 根据key获取Set中的所有值
     * @param key
     * @return
     */
    fun zSGet(key: String): Set<Any>? {
        return try {
            redisTemplate!!.opsForSet().members(key)
        } catch (e: Exception) {
            logger.error(key, e)
            null
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key
     * @param value
     * @return
     */
    fun zSHasKey(key: String, value: Any?): Boolean {
        return try {
            val result = redisTemplate?.opsForSet()?.isMember(key, value)
            return result?.get(key)?:false
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    fun zSSet(key: String, value: Any, score: Double): Boolean? {
        return try {
            redisTemplate!!.opsForZSet().add(key, value, 2.0)
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 将set数据放入缓存
     * @param key
     * @param time
     * @param values
     * @return
     */
    fun zSSetAndTime(key: String, time: Long, vararg values: Any?): Long {
        return try {
            val count = redisTemplate!!.opsForSet().add(key, *values)
            if (time > 0) expire(key, time)
            count!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }

    /**
     * 获取set缓存的长度
     * @param key
     * @return
     */
    fun zSGetSetSize(key: String): Long {
        return try {
            redisTemplate!!.opsForSet().size(key)!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }

    /**
     * 移除值为value的
     * @param key
     * @param values
     * @return
     */
    fun zSetRemove(key: String, vararg values: Any?): Long {
        return try {
            val count = redisTemplate!!.opsForSet().remove(key, *values)
            count!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }


    // ===================================list===================================


    // ===================================list===================================
    /**
     * 获取list缓存的内容
     * @取出来的元素 总数 end-start+1
     * @param key
     * @param start 开始 0 是第一个元素
     * @param end 结束 -1代表所有值
     * @return
     */
    fun lGet(key: String, start: Long, end: Long): List<Any>? {
        return try {
            redisTemplate!!.opsForList().range(key, start, end)
        } catch (e: Exception) {
            logger.error(key, e)
            null
        }
    }

    /**
     * 获取list缓存的长度
     * @param key
     * @return
     */
    fun lGetListSize(key: String): Long {
        return try {
            redisTemplate!!.opsForList().size(key)!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }

    /**
     * 通过索引 获取list中的值
     * @param key
     * @param index 索引 index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
     * @return
     */
    fun lGetIndex(key: String, index: Long): Any? {
        return try {
            redisTemplate!!.opsForList().index(key, index)
        } catch (e: Exception) {
            logger.error(key, e)
            null
        }
    }

    /**
     * 将list放入缓存
     * @param key
     * @param value
     * @return
     */
    fun lSet(key: String, value: Any): Boolean {
        return try {
            redisTemplate!!.opsForList().rightPush(key, value)
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 将list放入缓存
     * @param key
     * @param value
     * @param time
     * @return
     */
    fun lSet(key: String, value: Any, time: Long): Boolean {
        return try {
            redisTemplate!!.opsForList().rightPush(key, value)
            if (time > 0) expire(key, time)
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 将list放入缓存
     * @param key
     * @param value
     * @return
     */
    fun lSet(key: String, value: List<Any>?): Boolean {
        return try {
            redisTemplate!!.opsForList().rightPushAll(key, value)
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 将list放入缓存
     * @param key
     * @param value
     * @param time
     * @return
     */
    fun lSet(key: String, value: List<Any>?, time: Long): Boolean {
        return try {
            redisTemplate!!.opsForList().rightPushAll(key, value)
            if (time > 0) expire(key, time)
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key
     * @param index
     * @param value
     * @return
     */
    fun lUpdateIndex(key: String, index: Long, value: Any): Boolean {
        return try {
            redisTemplate!!.opsForList()[key, index] = value
            true
        } catch (e: Exception) {
            logger.error(key, e)
            false
        }
    }

    /**
     * 移除N个值为value
     * @param key
     * @param count
     * @param value
     * @return
     */
    fun lRemove(key: String, count: Long, value: Any?): Long {
        return try {
            val remove = redisTemplate!!.opsForList().remove(key, count, value!!)
            remove!!
        } catch (e: Exception) {
            logger.error(key, e)
            0
        }
    }
}